<template>
  <!-- 顶部提示框 -->
  <div
    v-if="alertMessage"
    :class="['alert', alertType, 'alert-dismissible', 'fade', 'show', 'alert-left']"
    role="alert"
    style="
      position: fixed;
      top: 20px;
      left: 50%;
      transform: translateX(-50%);
      z-index: 1050;
      width: 100%;
      max-width: 600px;
    "
  >
    <span
      class="alert-inner--icon"
      sytle="margin-left: 0px"
    >
      <i :class="alertIcon" />
    </span>
    <span class="alert-inner--text">
      <strong>{{ alertTitle }}</strong> {{ alertMessage }}
    </span>
    <button
      type="button"
      class="close"
      @click="clearAlert"
    >
      <span aria-hidden="true">&times;</span>
    </button>
  </div>

  <div class="my-container mt-4">
    <h3 class="mb-4">
      教学资料
    </h3>
    <hr class="divider">
    <div
      v-for="(chapter, index) in chapters"
      :key="index"
      class="card mb-3"
    >
      <!-- 章节标题 -->
      <div
        class="card-header d-flex justify-content-between align-items-center"
        style="cursor: pointer"
        @click="toggle(index)"
      >
        <strong>
          第 {{ index + 1 }} 章：{{ chapter.chapterName }}
          <span>{{ expandedIndex === index ? '▲' : '▼' }}</span>
        </strong>
      </div>

      <!-- 展开内容 -->
      <div
        v-if="expandedIndex === index"
        class="card-body"
      >
        <ul class="list-group mb-3">
          <li
            v-for="(item, i) in chapter.materials"
            :key="i"
            class="list-group-item d-flex justify-content-between align-items-center"
          >
            <div class="d-flex flex-row flex-grow-1">
              <div class="material-name">
                {{ getIcon(item.type) }} {{ item.materialName }}
              </div>
              <div class="fw-semibold ms-auto text-muted mt-1 mr-3">
                上传时间：{{ new Date(item.uploadTime).toLocaleString() }}
              </div>
            </div>

            <div class="d-flex gap-2">
              <button
                v-if="userRole === 'student'"
                class="btn btn-download"
                @click="downloadMaterial(item)"
              >
                学习
              </button>

              <button
                v-if="userRole === 'teacher'"
                class="btn btn-delete"
                @click="removeMaterial(index, i)"
              >
                删除
              </button>
            </div>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script setup>
  import { ref } from 'vue'
  import axios from 'axios'

  const route = useRoute()
  const courseId = route.params.id
  const expandedIndex = ref(null)
  const chapters = ref([])

  import { onMounted, onUnmounted } from 'vue'
  import emitter from '@/eventBus'

  import { useRoute } from 'vue-router'
  import { useRouter } from 'vue-router'
  import { useUserStore } from '@/stores/userStore'

  const userRole = ref('') // 保存后端返回的角色
  const router = useRouter()
  const userStore = useUserStore()
  const userId = userStore.user?.userId || ''
  async function fetchUserRole() {
    try {
      const res = await axios.get('/api/exercises/role', {
        params: {
          courseId,
          userId,
        },
      })
      userRole.value = res.data
      console.log('身份识别结果:', userRole.value)
    } catch (err) {
      console.error('获取用户身份失败', err)
      userRole.value = 'undefined'
    }
  }
  onMounted(fetchUserRole)
  // TeachingMaterial.vue (setup 中)
  async function fetchChaptersAndMaterials() {
    try {
      const res = await axios.get(`/api/courses/${courseId}/chapters`)
      chapters.value = res.data.map((ch) => ({
        chapterId: ch.chapterId,
        chapterName: ch.chapterName,
        materials: [],
      }))

      for (const chapter of chapters.value) {
        try {
          const matRes = await axios.get(`/api/materials/${courseId}/chapter/${chapter.chapterId}`)
          chapter.materials = matRes.data
        } catch (err) {
          console.error(`获取资料失败 for chapter ${chapter.chapterId}`, err)
          chapter.materials = []
        }
      }
    } catch (err) {
      console.error('获取章节信息失败：', err)
    }
  }

  async function markMaterialAsFinished(userId, materialId) {
    try {
      await axios.put('/api/materials/student/status', null, {
        params: {
          userId,
          materialId,
          isFinished: true,
        },
      })
      console.log('资料已标记为完成')
    } catch (err) {
      console.error('标记失败:', err)
    }
  }

  // 在页面挂载时请求每章资料
  onMounted(() => {
    fetchChaptersAndMaterials()

    emitter.on('material-uploaded', handleMaterialUploaded)
  })

  onUnmounted(() => {
    emitter.off('material-uploaded', handleMaterialUploaded)
  })

  function handleMaterialUploaded(payload) {
    console.log('收到上传成功事件:', payload)
    fetchChaptersAndMaterials() // 你已有的刷新逻辑
  }

  function toggle(index) {
    expandedIndex.value = expandedIndex.value === index ? null : index
  }

  async function removeMaterial(chapterIndex, materialIndex) {
    const ok = confirm('确定删除该资料？')
    if (!ok) return

    const material = chapters.value[chapterIndex].materials[materialIndex]

    try {
      // 假设你有后端 DELETE /api/materials/{id} 接口
      await axios.delete(`/api/materials/${material.materialId}`)

      // 成功后从前端移除
      chapters.value[chapterIndex].materials.splice(materialIndex, 1)
      // 删除成功
      showAlert('alert-success', '删除成功！', 'fas fa-check', '资料删除成功')
    } catch (err) {
      console.error('删除失败:', err)
      // 删除失败

      showAlert('alert-danger', '删除失败！', 'fas fa-times', err?.response?.data || err.message)
    }
  }

  async function downloadMaterial(item) {
    try {
      console.log('下载项：', item)
      const response = await axios.get(`/api/materials/${item.materialId}/download`, {
        responseType: 'blob',
      })

      let fileName = item.materialName || 'downloaded_file'

      // 创建 blob 对象
      const blob = new Blob([response.data])

      // 创建临时下载链接
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = fileName

      // 触发点击下载
      document.body.appendChild(link)
      link.click()

      // 尝试新标签页打开（有些文件会被下载而不是打开，这是浏览器行为）
      // window.open(link.href, '_blank')

      setTimeout(() => {
        URL.revokeObjectURL(link.href)
        document.body.removeChild(link)
      }, 10000)
      showAlert('alert-success', '下载成功！', 'fas fa-check', '资料下载成功')

      // ★★ 下载成功后标记为已完成
      await markMaterialAsFinished(userId, item.materialId)
    } catch (err) {
      // alert("下载失败：" + err?.response?.data || err.message);
      showAlert('alert-danger', '下载失败！', 'fas fa-times', err?.response?.data || err.message)
    }
  }

  function getIcon(type) {
    switch (type) {
      case 'pdf':
        return '📄'
      case 'ppt':
        return '📊'
      case 'doc':
        return '📃'
      case 'link':
        return '🔗'
      case 'excel':
        return '📈'
      default:
        return '📄'
    }
  }

  // 提示框内容和类型
  const alertMessage = ref('')
  const alertType = ref('alert-success') // Bootstrap class：'alert-danger'等
  const alertTitle = ref('Success!')
  const alertIcon = ref('fas fa-check') // 默认图标 ✅

  function showAlert(type, title, icon, message) {
    alertType.value = type
    alertTitle.value = title
    alertIcon.value = icon
    alertMessage.value = message

    setTimeout(() => {
      alertMessage.value = ''
    }, 3000) // 自动消失
  }

  function clearAlert() {
    alertMessage.value = ''
  }
</script>

<style scoped>
  .divider {
    border: none;
    height: 1px;
    background-color: #9d9d9d;
    margin: 8px 0 16px 0;
    border-radius: 4px;
  }

  .mb-4 {
    text-align: left;
    font-size: 35px;
  }

  .card-header {
    background-color: #104f91;
    color: white;
  }

  /* 弹窗样式 */
  .modal-backdrop {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.4);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
  }

  .modal-content-box {
    background-color: #fff;
    padding: 20px;
    border-radius: 8px;
    width: 400px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  }

  /* 按钮间隔 */
  .gap-2 > * + * {
    margin-left: 0.5rem;
  }

  .card {
    border: 1px solid #dee2e6;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    transition: transform 0.3s ease, box-shadow 0.3s ease;
    transform-origin: center center;
  }

  /* 鼠标悬停时放大 + 强化阴影 */
  .card:hover {
    transform: scale(1.05);
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
    z-index: 10;
  }

  .card-header {
    background-color: #326aa6;
    color: white;
    border-radius: 8px 8px 0 0;
    font-weight: 500;
    font-size: 18px;
  }

  .modal-content-box {
    border: 1px solid #ccc;
    border-radius: 10px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
  }

  .mb-4 {
    margin-bottom: 1.5rem !important;
  }

  .btn-download {
    background-color: #28a745; /* 绿色 */
    color: #fff;
    border: none;
    border-radius: 10px;
    transition: transform 0.2s ease, box-shadow 0.2s ease;
  }

  .btn-download:hover {
    transform: scale(1.1);
    box-shadow: 0 4px 10px rgba(40, 167, 69, 0.3);
  }

  .btn-delete {
    background-color: #dc3545; /* 红色 */
    color: #fff;
    border: none;
    border-radius: 10px;
    transition: transform 0.2s ease, box-shadow 0.2s ease;
  }

  .btn-delete:hover {
    transform: scale(1.1);
    box-shadow: 0 4px 10px rgba(220, 53, 69, 0.3);
  }

  .material-name {
    font-size: 1.1rem;
    font-weight: 500;
    color: #333;
  }

  .upload-btn {
    transition: transform 0.2s ease, box-shadow 0.2s ease;
  }

  .upload-btn:hover {
    transform: scale(1.1);
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
  }

  .upload-btn-lg {
    font-size: 1rem;
    font-weight: bold;
    background-color: #f8f9fa;
    border: 1px solid #ccc;
    padding: 8px 20px;
    border-radius: 8px;
    transition: transform 0.2s ease, box-shadow 0.2s ease;
  }

  .upload-btn-lg:hover {
    transform: scale(1.1);
    background-color: #e2e6ea;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }

  .alert-left {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    gap: 10px;
  }

  .alert-left .alert-inner--icon {
    margin-right: 6px;
    font-size: 18px;
  }

  .alert-left .alert-inner--text {
    text-align: left;
    flex: 1;
  }

  .my-container {
    max-width: 80vw !important;
    margin: 0 auto;
  }

  
</style>
